import json

from django_redis import get_redis_connection

from erp_system.models import PermissionsModel


def redis_storage_permissions(user):
    """
    把当前用户的权限信息，缓存到Redis数据库中
    Redis 中存放用户权限的结构为： user_用户ID---> 字典{key:path, value[列表] }
    """
    permission_ids = user.roles.values_list('permissions', flat=True).distinct()
    # 根据权限id，获取权限的所有的值，一级菜单的权限除外
    permissions = PermissionsModel.objects.filter(is_menu=False, id__in=permission_ids).values('id', 'path', 'method',
                                                                                               'name')
    if not permissions.exists():
        return None

    permissions_dict = {}  # 存放当前用户权限的字典
    for permission in permissions:
        # method = str(permission.get('method')).replace('\u200b', '')
        # path = str(permission.get('path')).replace('\u200b', '')
        # _name = str(permission.get('name')).replace('\u200b', '')
        # _id = permission.get('id')
        method = str(permission.get('method')).replace('\u200b', '')
        path = str(permission.get('path')).replace('\u200b', '')
        _name = str(permission.get('name')).replace('\u200b', '')
        _id = permission.get('id')
        if path in permission.get('path'):
            if path not in permissions_dict:
                permissions_dict[path] = []
            if not isinstance(permissions_dict[path],list):
                permissions_dict[path] = []
            permissions_dict[path].append({
                'method': method,
                'sign': _name,
                'id': _id,
            })
        # if path in permissions_dict:
        #     permissions_dict[path].append({
        #         'method': method,
        #         'sign': _name,
        #         'id': _id
        #     })

        else:
            permissions_dict[path] = [{
                'method': method,
                'sign': _name,
                'id': _id
            }]
    for key in permissions_dict:
        permissions_dict[key] = json.dumps(permissions_dict[key])
    # 存放到redis中
    redis_conn = get_redis_connection('default')  # 获得数据库的链接
    redis_conn.hmset(f'user_{user.id}', permissions_dict)  # 把当前用户所有权限插入到redis库中